package cn.yangtianxia.org.service.impl;

import cn.yangtianxia.basic.service.Impl.BaseServiceImpl;
import cn.yangtianxia.basic.util.MD5Utils;
import cn.yangtianxia.basic.util.StrUtils;
import cn.yangtianxia.org.domain.Employee;
import cn.yangtianxia.org.mapper.EmployeeMapper;
import cn.yangtianxia.org.service.IEmployeeService;
import cn.yangtianxia.user.domain.Logininfo;
import cn.yangtianxia.user.service.ILogininfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ILogininfoService logininfoService;

    @Override
    public Employee loadByUserName(String username) {
        return employeeMapper.loadByUserName(username);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);//认定类型是员工
        return logininfo;
    }
    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }
    /**
     * 我们在CUD user表的时候，需要级联操作logininfo，所以我们需要复写 save update  remove
     */
    @Override
    @Transactional
    public void save(Employee employee) {
        initEmployee(employee);
        //拷贝
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoService.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
        initRelationTable(employee);
    }

    private void initRelationTable(Employee employee) {
        employeeMapper.removeEmployeeRole(employee.getId());
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRoles());
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        //拷贝
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoService.update(logininfo);
        employeeMapper.update(employee);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Employee employee = employeeMapper.loadById(id);
        employee.getLogininfo_id();
        logininfoService.delete(employee.getLogininfo_id());
        employeeMapper.delete(id);
    }
}
